package com.david.andserver

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.david.andserver.util.FileUtils
import com.david.andserver.util.PathUtil
import com.david.core.event.MyEventBus
import com.david.core.event.Subscribe
import com.david.core.event.ThreadMode
import com.david.core.utils.PermissionUtils
import com.david.core.utils.ToastUtils
import com.david.core.utils.requestAllFilePermission


/**
 * TODO 无wifi时使用蓝牙实现服务功能
 * */
class MainActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var status:TextView
    private lateinit var navScan:View
    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (!ToastUtils.instance.isInited()) {
            ToastUtils.instance.init(applicationContext)
        }

        startForegroundService(Intent(this, ServerService::class.java))

        findViewById<View>(R.id.start_server).setOnClickListener(this)
        findViewById<View>(R.id.stop_server).setOnClickListener(this)
        findViewById<View>(R.id.qurk_video).setOnClickListener(this)
//        findViewById<View>(R.id.qurk_video).setOnLongClickListener(object :View.OnLongClickListener{
//            override fun onLongClick(v: View?): Boolean {
//                val intent = Intent(ACTION_VIEW)
//                intent.action= "android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION"
//                startActivity(intent)
//                return true
//            }
//
//        })

        status = findViewById(R.id.textview)

        MyEventBus.getDefault().register(this, "onServerStatus", ServerStatusEvent::class.java)

        status.text = "ip: ${NetInfo.getIpAddress(this)},server running:false"


        navScan = findViewById(R.id.nav_scan)
        navScan.setOnClickListener {
            val intent = Intent(this@MainActivity, WebQrCodeActivity::class.java)
            intent.putExtra("ip", NetInfo.ip);
            startActivity(intent)
        }



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 检查MANAGE_EXTERNAL_STORAGE权限
            // 检查MANAGE_EXTERNAL_STORAGE权限
            val manageExternalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.MANAGE_EXTERNAL_STORAGE)

            // 检查是否具有MANAGE_EXTERNAL_STORAGE权限

            // 检查是否具有MANAGE_EXTERNAL_STORAGE权限
            if (manageExternalStoragePermission == PackageManager.PERMISSION_GRANTED) {
                // 应用程序具有MANAGE_EXTERNAL_STORAGE权限
            } else {
                // 应用程序缺少MANAGE_EXTERNAL_STORAGE权限，可以向用户请求该权限
                ActivityCompat.requestPermissions(this, arrayOf<String>(Manifest.permission.MANAGE_EXTERNAL_STORAGE),
                    100)
            }
        } else {
            if (PermissionUtils.checkPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                FileUtils.getMusic(applicationContext)
                FileUtils.getVideo(applicationContext)
            } else {
                requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
            }

            requestAllFilePermission(this){
                if (it.resultCode == RESULT_CANCELED) {
                    ToastUtils.instance.toast("需要全部文件权限")
                } else if (it.resultCode == RESULT_OK){

                }
                //            if (it.data) {
                //
                //            }
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                FileUtils.getMusic(applicationContext)
                FileUtils.getVideo(applicationContext)
            }
        }
    }

    override fun onPause() {
        super.onPause()
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onClick(v: View?) {
        if (v != null) {
            val intent = Intent(this, ServerService::class.java)
            when(v.id) {
                R.id.start_server -> {
                    intent.putExtra(ServerService.SERVER_START_KEY, ServerService.SERVER_START_COMMAND)
                    navScan.visibility = View.VISIBLE
                }
                R.id.stop_server -> {
                    intent.putExtra(ServerService.SERVER_START_KEY, ServerService.SERVER_STOP_COMMAND)
                    navScan.visibility = View.GONE
                }
                R.id.qurk_video -> {
//                    PathUtil.checkFiles(Environment.getExternalStorageDirectory().absolutePath + "/Quark/Download")
                    PathUtil.createNetLinks()
                }
            }
            startForegroundService(intent)
        }

//        status.setText(ServerManager.)
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onServerStatus(serverStatusEvent: ServerStatusEvent){
        if (serverStatusEvent.isRunning) {
            status.text = "ip: ${NetInfo.getIpAddress(this)},server running:true"
        } else {
            status.text = "ip: ${NetInfo.getIpAddress(this)},server running:false"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        MyEventBus.getDefault().unregister(this, "onServerStatus", ServerStatusEvent::class.java)
    }
}